import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, Card, Select, Table, Space, message } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import {
  reqGetHospitalList,
  reqGetProvince,
  reqGetCoDoT,
  reqUpdateHosStatus,
} from '@api/hospitalList'
import {
  IhospitalList,
  IhospitalListItem,
  IdictList,
} from '@api/hospitalList/model/hospitalListTypes'
import { log } from 'console'
const { Option } = Select

let flag = false // 用于区分是否点击了查询按钮
export default function HospitalList() {
  const navigate = useNavigate()
  // list是表格数据
  const [list, setList] = useState<IhospitalList>([])
  // total是数据总数
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(2)

  // 省市区数据
  const [province, setProvince] = useState<IdictList>([])
  const [city, setCity] = useState<IdictList>([])
  const [district, setDistrcit] = useState<IdictList>([])
  // 医院类型状态
  const [hostype, setHostype] = useState<IdictList>([])

  // 正在请求数据的loading
  const [loading, setLoading] = useState(false)
  // 省,市,区,医院类型请求数据的loading
  const [provinceLoad, setProvinceLoad] = useState(false)
  const [cityLoad, setCityLoad] = useState(false)
  const [disLoad, setDisLoad] = useState(false)
  const [typeLoad, setTypeLoad] = useState(false)

  const [form] = Form.useForm()
  useEffect(() => {
    // 组件挂载,获取表格数据
    getHospitalList(1, 2)

    // 组件挂载,获取省数据
    getProvince()

    // 获取医院状态
    getHostype()
  }, [])

  // 封装获取表格数据的函数
  async function getHospitalList(page: number, limit: number) {
    setLoading(true)

    // 获取表单中用户选中的或填入的参数
    const params = form.getFieldsValue()

    let result
    if (flag) {
      result = await reqGetHospitalList({ page, limit, ...params })
    } else {
      result = await reqGetHospitalList({ page, limit })
    }

    setList(result.content)
    setTotal(result.totalElements)
    setLoading(false)
  }

  // 获取省数据
  async function getProvince() {
    setProvinceLoad(true)
    const result = await reqGetProvince()
    setProvince(result)
    setProvinceLoad(false)
  }
  // 获取市
  async function getCity(code: string) {
    setCityLoad(true)
    const result = await reqGetCoDoT(code)
    setCity(result)
    setCityLoad(false)
  }
  // 获取区
  async function getDistrict(code: string) {
    setDisLoad(true)
    const result = await reqGetCoDoT(code)
    setDistrcit(result)
    setDisLoad(false)
  }
  // 获取医院类型
  async function getHostype() {
    setTypeLoad(true)
    const result = await reqGetCoDoT()
    setHostype(result)
    setTypeLoad(false)
  }

  // 查询按钮的事件处理函数
  const onFinish = () => {
    flag = true
    getHospitalList(1, pageSize)
    setPage(1)
  }

  const columns: ColumnsType<IhospitalListItem> = [
    {
      title: '序号',
      render: (_, records, index) => index + 1,
      align: 'center',
      width: 80,
    },
    {
      title: '医院logo',
      render(_) {
        // 注意: 服务器响应回来的base64字符串没有前缀,所以我们需要额外添加
        return (
          <img src={'data:image/png;base64,' + _.logoData} alt="" width="80" />
        )
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(_) {
        return _.param.hostypeString
      },
    },
    {
      title: '详细地址',
      render(_) {
        return _.param.fullAddress
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render(_) {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                navigate('/syt/hospital/hospitallist/show', {
                  state: _.id,
                })
              }}
            >
              查看
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitallist/rules/${_.hoscode}`)
              }}
            >
              排班
            </Button>
            <Button
              type="primary"
              onClick={async () => {
                await reqUpdateHosStatus(_.id, _.status ? 0 : 1)
                message.success('修改医院状态成功')
                getHospitalList(page, pageSize)
              }}
            >
              {_.status ? '下线' : '上线'}
            </Button>
          </Space>
        )
      },
      width: 120,
    },
  ]
  return (
    <Card>
      <Form
        layout="inline"
        onFinish={onFinish}
        autoComplete="off"
        form={form}
        onValuesChange={() => {
          flag = false
        }}
      >
        <Form.Item name="provinceCode">
          <Select
            loading={provinceLoad}
            style={{ width: 200, marginBottom: 20 }}
            placeholder="请选择省"
            onChange={(value) => {
              // 清除市和区已选数据
              form.setFieldsValue({
                cityCode: undefined,
                districtCode: undefined,
              })
              getCity(value)
            }}
          >
            {province.map((item) => (
              <Option value={item.value} key={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            loading={cityLoad}
            style={{ width: 200 }}
            placeholder="请选择市"
            onChange={(value) => {
              // 清除区已选数据
              form.setFieldsValue({
                districtCode: undefined,
              })
              getDistrict(value)
            }}
          >
            {city.map((item) => (
              <Option value={item.value} key={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select
            style={{ width: 200 }}
            placeholder="请选择区"
            loading={disLoad}
          >
            {district.map((item) => (
              <Option value={item.value} key={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编码" />
        </Form.Item>
        <Form.Item name="hostype">
          <Select
            style={{ width: 200 }}
            placeholder="医院类型"
            loading={typeLoad}
          >
            {hostype.map((item) => (
              <Option value={item.value} key={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select style={{ width: 200 }} placeholder="医院状态">
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            icon={<SearchOutlined></SearchOutlined>}
          >
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            onClick={() => {
              // 1. 清空表单
              form.resetFields() //重置表单(由于默认表单为空,所以重置之后刚好表单呈现清空的效果)
              // 2. flag = false
              flag = false
              // 3. 重新获取表格数据,从第一页开始
              getHospitalList(1, pageSize)
              setPage(1)
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>
      <Table
        loading={loading}
        className="gap"
        columns={columns}
        dataSource={list}
        rowKey={'id'}
        pagination={{
          total,
          pageSize,
          current: page,
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10],
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange(page, pageSize) {
            setPage(page)
            setPageSize(pageSize)
            //获取表格数据
            getHospitalList(page, pageSize)
          },
        }}
      ></Table>
    </Card>
  )
}
